package com.javajun.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.javajun.custom.JqGridParm;
import com.javajun.custom.JqGridUtils;
import com.javajun.entity.Empower;
import com.javajun.entity.Enterprise;
import com.javajun.entity.EnterpriseAdmin;
import com.javajun.entity.UserRole;
import com.javajun.form.J2EnpriseAdminForm;
import com.javajun.service.EnterpriseAdminService;
import com.javajun.service.EnterpriseService;
import com.javajun.service.UserRoleService;

@Controller
@RequestMapping(value="enterpriseAdmin")
public class EnterpriseAdminController {

    @Autowired
    private EnterpriseAdminService enterpriseAdminService;
    @Autowired
    private UserRoleService userRoleService;
    @Autowired
    private EnterpriseService enterpriseService;
    
    private BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();

    /**
     * manage 映射地址/manage
     * @param map
     * @return
     */
    @RequestMapping(value="/manage")
    public String manage(ModelMap map) {
        return "enterpriseAdmin/manage";
    }
    
    @RequestMapping(value = "/getlist", method=RequestMethod.POST)
    // 返回json数据
    @ResponseBody
    public Object getList(JqGridParm parm) {
        Pageable pageable = parm.buildPageable();
        Page<EnterpriseAdmin> page = null;
        if (!parm.getSearch()) {
            page = enterpriseAdminService.findAll(pageable);
        } else {
            page = enterpriseAdminService.findAll(parm.buildSpec(), pageable);
        }
        HashMap<String, Object> pageResult = JqGridUtils.getPageResult(page);
        return pageResult;
    }
    
    @RequestMapping(value = { "/add", "/edit" }, method = RequestMethod.POST)
    @ResponseBody
    public Object addAndEdit(ModelMap map, String[] id, J2EnpriseAdminForm form) {
        // DateFormat timeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat timeFormat = new SimpleDateFormat("yyyy-MM-dd"); // 将时间格式化 
        // BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        Enterprise entity = new Enterprise();
        // 实例化一个 Empower 授权类，如果租户中没有授权，则将其赋值给租户
        Empower empower = new Empower();
        if (entity.getEmpower() == null) {
            entity.setEmpower(empower);
        }
        String mess = "";
        if (form.getOper().equals("add")) {
            Integer enterpriseId = null;
            save(enterpriseId, form);
            mess = "Add is OK!";
        } else if (form.getOper().equals("edit")) {
            Integer enterpriseId = null;
            for (int i = 0; i < id.length; i++) {
                System.out.println(id[i]);
                enterpriseId = Integer.parseInt(id[i]);
            }
            save(enterpriseId, form);
        } else if (form.getOper().equals("del")) {
            for (int i = 0; i < id.length; i++) {
                delete(map, Integer.parseInt(id[i]));
                System.out.println("删除用户id：" + id[i]);
                //System.out.println("下一个即将删除的用户id:" + id[i+1]);
            }
            mess = "Delete is OK!";
            System.out.println(mess);
        }
        return mess;
    }

    /**
     * Delete 删除一个租户管理员
     * @param map
     * @param id
     */
    private void delete(ModelMap map, Integer id) {
        if (id != null) {
            // EnterpriseAdmin enterpriseAdmin = enterpriseAdminService.findById(id);
            // enterpriseAdminService.delete(enterpriseAdmin);
            enterpriseAdminService.deleteById(id);
        }
    }

    private void save(Integer id, J2EnpriseAdminForm form) {
        // 时间格式化格式
        SimpleDateFormat timeFormat = new SimpleDateFormat("yyyy-MM-dd");

        EnterpriseAdmin enterpriseAdmin = new EnterpriseAdmin();
        if (id != null) { // 当id不为空时，表示修改
            enterpriseAdmin = enterpriseAdminService.findById(id);
            enterpriseAdmin.setName(form.getName());
            enterpriseAdmin.setEmail(form.getEmail());
            enterpriseAdmin.setUsername(form.getEmail());
            enterpriseAdmin.setTel(form.getTel());
            
            // 租户管理员设置角色
            if (enterpriseAdmin.getRoles() == null) {
                List<UserRole> roles = new ArrayList<>();
                enterpriseAdmin.setRoles(roles);
            }
            enterpriseAdmin.getRoles().add(userRoleService.findByCode("ROLE_ENTERPRISEADMIN"));
            enterpriseAdminService.save(enterpriseAdmin);
        } else {
            Enterprise enterprise = new Enterprise();
            Empower empower = new Empower();
            enterprise.setEmpower(empower);
            // EnterpriseAdmin enterpriseAdmin = new EnterpriseAdmin();
            enterprise.setEnterpriseAdmin(enterpriseAdmin);

            // 租户相关
            // 1.租户名字
            if (StringUtils.hasText(form.getEnterprise().getName())) {
                enterprise.setName(form.getEnterprise().getName());
            }
            
            // 授权相关
            // 1.授权起始时间
            // 2.授权结束时间
            // 3.授权金额
            String startTimeStr = form.getEnterprise().getEmpower().getFormatStartTime();
            String endTimeStr = form.getEnterprise().getEmpower().getFormatEndTime();
            Double payMoney = form.getEnterprise().getEmpower().getPayMoney();
            if (StringUtils.hasText(startTimeStr)) {
                Date time = new Date();
                try {
                    time = timeFormat.parse(startTimeStr);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                enterprise.getEmpower().setStartTime(time);
            }
            
            if (StringUtils.hasText(endTimeStr)) {
                Date time = new Date();
                try {
                    time = timeFormat.parse(endTimeStr);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                enterprise.getEmpower().setEndTime(time);
            }
            
            if (payMoney != null) {
                enterprise.getEmpower().setPayMoney(payMoney);
            }
            
            // 租户管理员相关
            // 1.租户管理员名字
            // 2.租户管理员邮箱
            // 3.租户管理员联系电话
            // TODO 4.管理员面
            
            if (StringUtils.hasText(form.getName())) {
                enterprise.getEnterpriseAdmin().setName(form.getName());
            }
            
            if (StringUtils.hasText(form.getEmail())) {
                enterprise.getEnterpriseAdmin().setEmail(form.getEmail());
                enterprise.getEnterpriseAdmin().setUsername(form.getEmail()); // 租户管理员的用户名和邮箱一样
            }
            
            if (StringUtils.hasText(form.getTel())) {
                enterprise.getEnterpriseAdmin().setTel(form.getTel());
            }
            if (enterpriseAdmin.getRoles() == null) {
                List<UserRole> roles = new ArrayList<>();
                enterprise.getEnterpriseAdmin().setRoles(roles);
            }
            enterprise.getEnterpriseAdmin().getRoles().add(userRoleService.findByCode("ROLE_ENTERPRISEADMIN"));

            enterprise.getEnterpriseAdmin().setPassword(encoder.encode("1111"));
            
            enterpriseService.save(enterprise);
/*            // 如果租户信息为空，
            if (enterpriseAdmin.getEnterprise() == null) {
                Enterprise enterprise = new Enterprise();
                enterpriseAdmin.setEnterprise(enterprise);
                
                // 如果授权信息为空，则实例化一个
                if (enterpriseAdmin.getEnterprise().getEmpower() == null) {
                    Empower empower = new Empower();
                    enterpriseAdmin.getEnterprise().setEmpower(empower);
                }
            }
            
            // 租户管理员相关
            // 1.名字
            // 2.邮箱
            // 3.联系电话
            enterpriseAdmin.setName(form.getName());
            enterpriseAdmin.setEmail(form.getEmail());
            enterpriseAdmin.setEmail(form.getEmail()); // 用户名与密码相同
        
            // 租户相关
            // 1.租户名字
            enterpriseAdmin.getEnterprise().setName(form.getEnterprise().getName());
            
            // 授权相关
            // 1.授权起始时间
            // 2.授权结束时间
            // 3.授权金额
            if (StringUtils.hasText(form.getEnterprise().getEmpower().getFormatStartTime())) {
                Date time = new Date();
                try {
                    time = timeFormat.parse(form.getEnterprise().getEmpower().getFormatStartTime());
                    
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                enterpriseAdmin.getEnterprise().getEmpower().setStartTime(time);
            }
            
            if (StringUtils.hasText(form.getEnterprise().getEmpower().getFormatEndTime())) {
                Date time = new Date();
                try {
                    time = timeFormat.parse(form.getEnterprise().getEmpower().getFormatEndTime());
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                enterpriseAdmin.getEnterprise().getEmpower().setEndTime(time);
            }
            
            if (form.getEnterprise().getEmpower().getPayMoney() != null) {
                enterpriseAdmin.getEnterprise().getEmpower().setPayMoney(form.getEnterprise().getEmpower().getPayMoney());
            }
*/            
        }
        
    }
}
